<template>
	<view>
		<view :style="[top]" class="top"><view class="title">购物车</view></view>
		<!-- 顶部组件 -->
		<view class="nav-bar" v-show="showNavBar">
			<u-navbar :is-back="false" :background="{ background: '#fff' }" border-bottom id="nav-bar" title="购物车"></u-navbar>
		</view>
		<!-- 未登录 -->
		<view class="no-goods" v-if="!isLogin">
			<image src="https://vkceyugu.cdn.bspapp.com/VKCEYUGU-weitao/af4ee070-abaf-11ea-9e8b-05a3242b26f2.png" mode=""></image>
			<view>登录之后才可以使用购物车哦~</view>
			<view class="btn" @click="navigateTo('login')">去登录</view>
		</view>
		<!-- 没有商品 -->
		<view class="no-goods" v-if="isLogin && goodsIds.length == 0">
			<image src="https://vkceyugu.cdn.bspapp.com/VKCEYUGU-weitao/af4ee070-abaf-11ea-9e8b-05a3242b26f2.png" mode=""></image>
			<view>购物车还没有商品哦~</view>
			<view class="btn" @click="navigateTo('home')">去逛逛</view>
		</view>
		<!-- 有商品 -->
		<view class="have-goods" id="have_goods" v-if="isLogin && goodsArr.length != 0">
			<view class="shop-card">
				<view class="shop-title u-flex">
					<image :src="allSelected ? checked_img : unchecked_img" class="checked-img" @click="selectAll"></image>
					<text class="title">微淘精选</text>
					<view @click="tips()" class="tips">
						<image src="../../../static/tips.png" mode=""></image>
						<text>{{totalPrice >= 99 ? '已' : '满99元'}}免运费</text>
					</view>
				</view>
				<view class="goods-box u-flex" v-for="(item, index) in goodsIds" :key="index">
					<image :src="item.checked ? checked_img : unchecked_img" class="checked-img" @click="selectGoods(item)"></image>
					<view class="goods-img"><image :src="item.img" mode="aspectFill"></image></view>
					<view class="detail">
						<view class="name u-line-2">
							<text class="label" v-for="litem in item.labels" :key="litem.labelId" :style="{color:litem.attrs.bgColor,borderColor:litem.attrs.bgColor}">
								{{litem.text}}
							</text>
							{{ item.name || ''}}
						</view>
						<view class="props-box u-line-1" v-if="item.props.length > 0">
							<text class="prop u-line-1" v-for="(pitem, pindex) in item.props" :key="pindex">{{ pitem }}</text>
						</view>
						<view class="price-box u-flex">
							<view class="price" v-if="item.price">￥{{ item.price }}</view>
							<view class="count">
								<u-number-box
									:input-width="42"
									:input-height="42"
									:size="22"
									bg-color="#fbfbfb"
									color="#666"
									:min="1"
									:max="9"
									:value="item.count"
									:index="index"
									@change="changeCount(item, $event)"
								></u-number-box>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		<!-- 结算 -->
		<view class="settlement" v-if="goodsIds.length != 0">
			<view @click="selectAll">
				<image :src="allSelected ? checked_img : unchecked_img" class="select_img"></image>
				<view>全选</view>
			</view>
			<view class="confirm">
				<view>
					合计：
					<text>￥{{ totalPrice }}</text>
				</view>
				<view @click="confirm()">
					结算
					<text v-if="totalQuantity">({{ totalQuantity }})</text>
				</view>
			</view>
		</view>
		<!-- 推荐商品 -->
		<mi-goods-list :dataList="goodsList" :loadMoreBg="loadingBg" :showLoadmore="showLoadmore" :loadMoreStatus="loadingStatus"></mi-goods-list>
		<mi-toast ref="miToast" />
	</view>
</template>

<!-- 购物车逻辑 -->
<!--
1、当购物车中没有商品时，显示默认图片。
2、点击全选，即可选中全部商品，合计为所有商品的价格，结算按钮上显示所选商品总数量，再次点击全选，还原默认状态
3、点击选中单个商品，合计价格为当前选择的商品价格乘以当前商品所选数量，结算按钮显示当前商品所购买的数量
4、商品数量默认为1，-号为不可点击状态，当数量大于1时，可点击。当商品数量减少到1时，再次变为不可点击，同时Toast提示不能再减少
5、增加商品数量时，当所选商品总数达到商品限购数量或者最大库存，变为不可点击状态，同时显示对应的Toast提示
6、选择商品规格，规格选择完成后，页面的商品单价随所选规格变化
7、点击编辑，页面恢复默认状态，同时结算按钮变为删除，选中商品，点击删除按钮即可移出购物车 
-->

<script>
import miGoodsList from '@/components/mi-goods-list.vue'
export default {
	data() {
		return {
			showNavBar: false,
			navBarBottom: false,
			top: {},
			goodsIds: [],
			idsArrLength: 0,
			goodsArr: [],
			goodsList: [],
			shopList: [],
			dataOffset: 0,
			showLoadmore: false,
			loadingStatus: 'loadmore',
			loadingBg: '#f7f7f7',
			checked_img: '/static/checked.png',
			unchecked_img: '/static/unchecked.png',
		}
	},
	components: {
		miGoodsList
	},
	onLoad() {
		this.getSystemInfo()
		this.getRecGoods()
	},
	onShow() {
		if (this.isLogin) {
			uni.showLoading({
				title: '加载中...'
			})
			this.getCartGoodsId()
		}
	},
	methods: {
		getCartGoodsId() {
			uniCloud.callFunction({
				name: 'getCartGoodsId',
				data: { openid:this.userInfo.openid },
				success: res => {
					console.log(res.result)
					if (res.result.code == -1 || res.result.data.length == 0) return uni.hideLoading()
					this.goodsIds = res.result.data
					let idsArr = []
					res.result.data.forEach(x => {
						if (idsArr.indexOf(x.gid) == -1) {
							idsArr.push(x.gid)
						}
					})
					this.goodsArr = []
					for (let i = 0; i < idsArr.length; i++) {
						this.getGoodsInfo(idsArr[i], idsArr.length)
					}
					uni.hideLoading()
				},
				fail: err => {
					console.log(err)
					this.$refs.miToast.show({
						title: '获取购物车信息失败,请刷新重试',
						type: 'error',
						url: ''
					})
					uni.hideLoading()
				}
			})
		},
		getGoodsInfo(gid, idsArrLength) {
			this.$u.api.getGoodsDetail({gid}).then(res => {
				this.addGoodsData(res.data.goods, idsArrLength)
			})
		},
		// 为了获取加入购物车的商品规格，此处使用了获取商品详情页的接口
		// 实际中，添加购物车把商品规格直接加入数据库中，再获取就比较方便了
		// 处理商品数据，整理格式
		addGoodsData(goods, idsArrLength) {
			this.goodsArr.push(goods)
			if (this.goodsArr.length == idsArrLength) {
				console.warn('请求结束')
				// 把对应商品数据保存进原数组
				this.goodsIds.forEach(idx => {
					this.goodsArr.forEach(arrx => {
						if (idx.gid == arrx.goodsInfo.gid) {
							this.$set(idx, 'goods', arrx)
						}
					})
				})
				this.goodsIds.forEach(x => {
					x.name = x.goods.goodsInfo.name
					x.price = x.goods.productInfo[x.pid].price / 100
					x.img = x.goods.productInfo[x.pid].img
					if (x.goods.labels && x.goods.labels.length != 0) {
						x.labels = x.goods.labels
					}
					if (x.goods.propTags.length != 0) {
						x.tids = []
						const tids = x.goods.propTags.filter(item => item.pid == x.pid)
						for (var i = 0; i < tids.length; i++) {
							x.tids.push(tids[i].tid)
						}
					}
					if (x.goods.shopTags.length != 0) {
						x.props = []
						for (var i = 0; i < x.tids.length; i++) {
							x.goods.shopTags.forEach(item => {
								let props = item.tags.filter(tag => tag.tid == x.tids[i])
								if (props.length != 0) {
									x.props.push(props[0].name)
								}
							})
						}
					}
					// if (x.goods.brand) {
					// 	x.brand = x.goods.brand
					// }
					this.$delete(x, 'tids')
					this.$delete(x, 'goods')
				})
				// 按店铺划分商品
				// let shopArr = []
				// this.goodsIds.forEach(x => {
				// 	const shopArrData = {
				// 		brandName: x.brand.brandName,
				// 		brandId: x.brand.brandId,
				// 		brandLogo: x.brand.brandLogo,
				// 		goods: []
				// 	}
				// 	shopArr.push(shopArrData)
				// })
				// var newobj = {}
				// this.shopList = []
				// for (var i = 0; i < shopArr.length; i++) {
				// 	var item = shopArr[i]
				// 	if (!newobj[item['brandId']]) {
				// 		newobj[item['brandId']] = this.shopList.push(item)
				// 	}
				// }
				// this.shopList.forEach(x => {
				// 	x.goods.push(...this.goodsIds.filter(item => item.brand.brandId == x.brandId))
				// })
			}
		},
		getSystemInfo() {
			uni.getSystemInfo({
				success: res => {
					let menuInfo = uni.getMenuButtonBoundingClientRect()
					const topHeight = menuInfo.top * 2 - res.safeArea.top + menuInfo.height
					// console.log('最终高度为:' + topHeight + 'px')
					this.$set(this.top, 'height', topHeight + 'px')
					this.$set(this.top, 'paddingTop', res.safeArea.top + 'px')
				}
			})
		},
		getRecGoods() {
			let data = {
				type: 7,
				offset:this.dataOffset,
				limit:20
			}
			this.$u.api.getRecommendGoods(data).then(res => {
				res.data.recommendResponseList.forEach(x => {
					this.goodsList.push(x.data.goods)
				})
				this.dataOffset += data.limit
				this.showLoadmore = true
				this.loadingStatus = 'loadmore'
			})
		},
		navigateTo(url) {
			switch (url) {
				case 'login':
					uni.navigateTo({
						url: '../../user/login/login'
					})
					break
				case 'home':
					uni.switchTab({
						url: '../index/index'
					})
			}
		},
		changeCount(item, e) {
			// console.log('触发了')
			// uni.showLoading()
			// console.log(e.value)
			const newCount = parseInt(e.value)
			uniCloud.callFunction({
				name: 'updateCartCount',
				data: {
					openid: this.userInfo.openid,
					goods: {
						gid: item.gid,
						pid: item.pid,
						newCount
					}
				},
				success: () => {
					// console.log(res.result)
					uni.hideLoading()
					// this.goodsIds[e.index].count = newCount
					// item.count = newCount
				},
				fail: () => {
					this.$refs.miToast.show({
						title: '修改数量失败，请重试',
						type: 'error'
					})
				}
			})
		},
		selectGoods(item) {
			item.checked = !item.checked
		},
		selectAll() {
			if (this.allSelected) {
				this.goodsIds.forEach(x => {
					x.checked = false
				})
			} else {
				this.goodsIds.forEach(x => {
					x.checked = true
				})
			}
		},
		/* 结算按钮 */
		confirm: function() {
			if (this.goodsIds.filter(x => x.checked).length !== 0) {
				this.$refs.miToast.show({
					title: '当前结算价格为：' + this.totalPrice,
					type: 'success'
				})
			} else {
				this.$refs.miToast.show({
					title: '暂未选择商品~',
					type: 'warning'
				})
			}
		},
		tips() {
			uni.showModal({
				title: '邮费说明',
				content: '微淘精选商品，即微淘配送和第三方商家发货的商品，2020年1月1日起，单笔订单满99元免运费，不满99元收10元运费。',
				showCancel: false,
				confirmText: '我知道了',
				confirmColor: '#845d32'
			})
		}
	},
	onPageScroll(e) {
		this.showNavBar = e.scrollTop > 30 ? true : false
	},
	onReachBottom() {
		if (this.dataOffset >= 120) {
			return (this.loadingStatus = 'nomore')
		}
		this.loadingStatus = 'loading'
		this.getRecGoods()
	},
	computed: {
		totalPrice() {
			let totalFee = 0
			this.goodsIds.forEach(x => {
				if (x.checked) {
					totalFee += x.price * x.count
				}
			})
			return totalFee.toFixed(2)
		},
		totalQuantity() {
			let quantity = 0
			this.goodsIds.forEach(x => {
				if (x.checked) {
					quantity += x.count
				}
			})
			return quantity
		},
		allSelected() {
			return this.goodsIds.filter(x => x.checked).length == this.goodsIds.length ? true : false
		}
	}
}
</script>

<style lang="scss">
page {
	background-color: #f7f7f7;
}
.top {
	// position: fixed;
	top: 0;
	width: 100%;
	color: #ffffff;
	background: url('https://vkceyugu.cdn.bspapp.com/VKCEYUGU-weitao/2d0ca750-0e3d-11eb-b244-a9f5e5565f30.png') no-repeat center / 100% 100%;
	z-index: 1;
	display: flex;
	align-items: center;
	justify-content: center;
	.title {
		font-size: 32rpx;
		letter-spacing: 2rpx;
		font-weight: bold;
	}
}
.nav-bar {
	position: fixed;
	width: 750rpx;
	z-index: 1;
}
// .have_goods_top {
// 	height: 86rpx;
// 	color: #333;
// 	font-size: 22rpx;
// 	background: #ffffff;
// 	opacity: 0;
// 	transition: 0.5s;
// 	box-shadow: 0 2px 5px #f1f1f1;
// 	view:nth-child(1) {
// 		line-height: 86rpx;
// 		font-size: 30rpx;
// 		text-align: center;
// 	}
// 	view:nth-child(2) {
// 		right: 28rpx;
// 		font-size: 26rpx;
// 	}
// }
.have-goods {
	// margin-top: 100rpx;
	padding: 0 20rpx;
	background: url(http://bd.zhichi921.com/attachment/weitao/cart_goods_bg.png) no-repeat top / 750rpx 212rpx;
	// height: 600rpx;
	overflow: hidden;
	font-size: 32rpx;
	.shop-card {
		// width: 716rpx;
		margin: 20rpx auto 36rpx;
		background-color: #fff;
		border-radius: 12rpx;
		padding: 24rpx 28rpx 30rpx 18rpx;
		.shop-title {
			margin-bottom: 30rpx;
			.title {
				font-size: 32rpx;
				color: #2d2d2d;
				font-weight: bold;
				margin-left: 14rpx;
				font-family: Pingfang-Regular;
			}
			.tips {
				margin-left: auto;
				image {
					width: 23rpx;
					height: 23rpx;
				}
				text {
					font-size: 28rpx;
					color: #666;
					margin-left: 8rpx;
				}
			}
		}
	}
}
.checked-img {
	min-width: 34rpx;
	width: 34rpx;
	height: 34rpx;
}
.goods-box {
	position: relative;
	margin-bottom: 72rpx;
	.goods-img {
		width: 156rpx;
		height: 156rpx;
		min-width: 156rpx;
		margin: 0 20rpx;
		border-radius: 12rpx;
		overflow: hidden;
		background-color: #f8f8f8;
		image {
			width: inherit;
			height: inherit;
		}
	}
	.detail {
		flex: 1;
		// display: flex;
		// flex-direction: column;
		max-width: 440rpx;
		height: 156rpx;
		color: #333;
		font-size: 26rpx;
		.label{
			padding: 0 6rpx;
			margin-right: 6rpx;
			font-size: 22rpx;
			border-radius: 12rpx;
			color: #BF1111;
			border: 1.5rpx solid #bf1111;
		}
		.name {
			line-height: 36rpx;
			height: 78rpx;
		}
		.props-box {
			max-width: 100%;
			display: inline;
			// align-items: center;
			height: 36rpx;
			margin-top: 6rpx;
			border-radius: 8rpx;
			font-size: 22rpx;
			color: #666;
			background-color: #f7f7f7;
			.prop {
				margin: 0 12rpx;
				// margin-right:16rpx;
				// overflow: hidden;
				// text-overflow:ellipsis;
				// white-space: nowrap;
			}
		}
		.price-box {
			margin-top: 10rpx;
			justify-content: space-between;
			.price {
				color: #bf1111;
			}
		}
	}
}

.goods_count {
	position: absolute;
	bottom: 0;
	right: 0;
	display: flex;
	justify-content: space-between;
	align-items: center;
	width: 120rpx;
	view {
		width: 54rpx;
		height: 40rpx;
		border-radius: 6rpx;
		line-height: 40rpx;
		text-align: center;
		background-color: #f4f4f4;
		color: #222;
	}
	image {
		width: 16rpx;
		height: 16rpx;
	}
	image:nth-child(1) {
		height: 4rpx;
	}
}
.no-goods {
	margin-top: 20rpx;
	text-align: center;
	font-size: 26rpx;
	image {
		width: 162rpx;
		height: 162rpx;
		margin-top: 54rpx;
	}
	view {
		color: #777;
		margin: 24rpx auto;
	}
	.btn {
		width: 190rpx;
		height: 60rpx;
		border: 1rpx solid #d3c2a8;
		border-radius: 30rpx;
		color: #b8996a;
		margin: 0 auto 54rpx;
		line-height: 56rpx;
	}
}
.settlement {
	position: fixed;
	display: flex;
	align-items: center;
	justify-content: space-between;
	bottom: var(--window-bottom);
	left: 0;
	height: 100rpx;
	width: 750rpx;
	border-top: 1rpx solid #efefef;
	border-bottom: 1rpx solid #efefef;
	background-color: #fff;
	z-index: 1;
	font-size: 26rpx;
	color: #333;
	& > view {
		display: flex;
		align-items: center;
	}
	image {
		margin: 0 12rpx 0 21rpx;
	}
	.confirm {
		font-weight: bold;
		view:nth-child(1) text {
			color: #b90000;
		}
		view:nth-child(2) {
			width: 176rpx;
			height: 70rpx;
			margin: 0 16rpx;
			text-align: center;
			line-height: 70rpx;
			font-size: 28rpx;
			font-family: Pingfang-Regular;
			color: #fff;
			border-radius: 35rpx;
			background: linear-gradient(left, #f04c2d, #d61111);
		}
	}
}
.select_img {
	width: 34rpx;
	height: 34rpx;
}
</style>
